from fastapi import APIRouter, Depends

from apps.system import cruds, schemas
from core.auth import Auth, FullAdminAuth
from core.dependencies import IdList
from core.response import SuccessResponse

router = APIRouter(prefix="/dept")


@router.get("/list", summary="获取部门列表")
async def list_depts(
        auth: Auth = Depends(FullAdminAuth(permissions=["auth.dept.list"]))
):
    datas = await cruds.DeptDal(auth.db).get_tree_list(mode=1)
    return SuccessResponse(datas)


@router.get("/options", summary="获取部门树选择项")
async def list_dept_options(
        auth: Auth = Depends(FullAdminAuth())
):
    return SuccessResponse(await cruds.DeptDal(auth.db).get_tree_list(mode=3))


@router.post("/create", summary="创建部门")
async def create_dept(
        data: schemas.Dept,
        auth: Auth = Depends(FullAdminAuth(permissions=["auth.dept.create"]))
):
    return SuccessResponse(
        await cruds.DeptDal(auth.db).create_data(data=data),
        msg="创建成功"
    )


@router.put("/update/{data_id}", summary="更新部门")
async def update_dept(
        data_id: int,
        data: schemas.Dept,
        auth: Auth = Depends(FullAdminAuth(permissions=["system.dept.update"]))
):
    return SuccessResponse(
        await cruds.DeptDal(auth.db).put_data(data_id, data),
        msg="修改成功"
    )


@router.delete("/delete", summary="批量删除部门", description="硬删除, 如果存在用户关联则无法删除")
async def delete_depts(
        ids: IdList = Depends(),
        auth: Auth = Depends(FullAdminAuth(permissions=["auth.dept.delete"]))
):
    await cruds.DeptDal(auth.db).delete_datas(ids.ids, v_soft=False)
    return SuccessResponse(msg="删除成功")
